#!/usr/bin/env node
const http = require('http'),
    fs = require('fs'),
    qs = require('querystring'),
    log = console.log;
//先写调用 在写定义


let items = [],
result={
    status:200,
    reason:'ok',
    data:[],
    conut:0
} //这里是返回的数据 给一个默认值

http.createServer((req, res) => {
    // console.log(req.method);
    logRequest(req);//打印起始行和请求头
    if (req.url.slice(0, 5) !== '/todo') {
        let html =fs.readFileSync('./aaa.html').toString('utf8');
        if(req.url==='/'){
            res.end(html);
        } 
        else if(req.url ==='/12-todo.js'){
            fs.createReadStream('./12-todo.js').pipe(res);
            //把文件的内容传了过去 这样浏览器就会执行前端的脚本
        }
        else{
            res.end('not api');
        }
        return 
    }

    switch (req.method) {
        case 'GET':
            select(req, res);
            break;
        case 'POST':
            insert(req, res)
            break;
            //curl -X POST -d 'item=eat' 加网址
        case 'PUT':
            update(req, res);
            break;
        case 'DELETE':
           remove(req,res);
            break;
        default:
            res.end('cuole')
        // res.end(`${req.method}`)
    }

}).listen(8080);
function select (req,res){
    result.data = items;
    res.end(JSON.stringify(result));
    //这里是返回所有数据

}
function insert (req,res){
    let data = '';
    req.on('data',chunk => data+=chunk);//箭头函数
    req.on('end',()=>{
        let item = qs.parse(data).item;
        if(item!=='' && typeof item !== undefined){
            items.push(item);
            res.end(JSON.stringify(result));

        }
        else{
            result.status=401;
            result.reason='item is empty';
            res.end(JSON.stringify(result));
        }

    })
}
function update (req,res){

    let id =req.url.split(':')[1];
    //id得进行验证 type 值 min max 
    let data ='' ;
    req.on('data',chunk =>data+=chunk);
    req.on('end',()=>{
        let item = qs.parse(data).item;
        if(item !== '' && typeof item!==undefined){
            items[id] = item;
            res.end(JSON.stringify(result))
        }
        else{
            result.status=402
            result.reason='chucuole '
            res.end(JSON.stringify(result));   
        }
    })
    let item = items[id];
    res.end(req.method);
}
function remove (req,res){
    
    //id not exist
    
    //get id 
    let id = req.url.split(':')[1];
    if(typeof id === 'undefined'){
        items=[];
        result.status=200;
        result.reason='ok';
        res.end(JSON.stringify(result));
    }

    items = items.splice(id,1);
    result.status=200;
    result.reason='del ok';
    res.end(JSON.stringify(result));

    


    //id exist
    //验证id id的范围 id不能为空
    //id is ok 就删除啊items[id]
    res.end(req.method);
}
function logRequest(req) {
    log(`${req.method}`);
    log(req.url);
    log(req.httpVersion);
}
// fetch('http://192.168.126.144:8080/todo',{method:'POST',body:'item=shoss'}).then(res => { res.text().then(txt => console.log(txt)) });
// fetch('http://192.168.126.144:8080/todo',{method:'PUT',body:'item=LRARNING'}).then(res => { res.text().then(txt => console.log(txt)) });

